// db.js
import mariadb from "mariadb";
import "dotenv/config";

// Create a MariaDB connection pool. The project uses ESM (see package.json).
export const pool = mariadb.createPool({
  host: process.env.DB_HOST || "localhost",
  port: Number(process.env.DB_PORT || 3306),
  user: process.env.DB_USER || "root",
  password: process.env.DB_PASSWORD || "",
  database: process.env.DB_DATABASE || "test",
  connectionLimit: 5,
});

// Helper: test that we can get a connection and run a simple SELECT 1
export async function testConnection() {
  let conn;
  try {
    conn = await pool.getConnection();
    const rows = await conn.query("SELECT 1 AS ok");
    return rows && rows[0] && rows[0].ok === 1;
  } catch (err) {
    // Log a concise, human-friendly message for the caller to surface
    console.error("DB connection test failed:", err.message || err);
    return false;
  } finally {
    if (conn) conn.release();
  }
}
